package room;

import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.IoFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

/**
 * Created by hasee on 2016/9/23.
 */
public class MinaServerHandler  extends IoHandlerAdapter {

    @Override
    /**
     * session创建时
     */
    public void sessionCreated(IoSession session) throws Exception {
        String[] address = session.getRemoteAddress().toString().split(":");
        MinaServer.names.put(session,address[1]);
        session.write(address[1]+"已进入聊天室");
    }

    @Override
    /**
     * session打开时
     */
    public void sessionOpened(IoSession session) throws Exception {

    }

    @Override
    /**
     * 接收到消息时
     */
    public void messageReceived(IoSession session, Object message) throws Exception {
        String content = message.toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String datetime = sdf.format(new Date());


        // 拿到所有的客户端Session
        Collection<IoSession> sessions = session.getService().getManagedSessions().values();
        // 向所有客户端发送数据
        for (IoSession sess : sessions) {
            String name = MinaServer.names.get(session);
            sess.write(name+"\t"+datetime + "\t" + content);
        }
    }

    @Override
    /**
     * 发送消息时
     */
    public void messageSent(IoSession session, Object message) throws Exception {
        System.out.println(message);
    }


    @Override
    /**
     * session关闭时
     */
    public void sessionClosed(IoSession session) throws Exception {
        CloseFuture closeFuture = session.close(true);
        closeFuture.addListener(new IoFutureListener<IoFuture>() {
            public void operationComplete(IoFuture future) {
                if (future instanceof CloseFuture) {
                    ((CloseFuture) future).setClosed();
                }
            }
        });
    }

    @Override
    /**
     * session闲置时
     */
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        super.sessionIdle(session, status);
    }

    @Override
    /**
     * 捕捉到异常时
     */
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        System.out.println(cause);
    }

}

